package com.lst.tools.mybatis.injector.methods;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.lst.tools.mybatis.mapper.ExpandBaseMapper;
import com.lst.tools.mybatis.utils.ExpandSqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @author: Frank
 * @date: 2019/9/26 14:15
 * @version: V1.0
 */
public class InsertNotExist extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String prefix = StringUtils.join(ExpandBaseMapper.ENTITY_PARAM_NAME, ".");
        KeyGenerator keyGenerator = new NoKeyGenerator();
        String columnScript = SqlScriptUtils.convertTrim(ExpandSqlUtils.getAllInsertSqlColumnMaybeIf(tableInfo, prefix), "(", ")", null, ",");
        String valuesScript = SqlScriptUtils.convertTrim(ExpandSqlUtils.getAllInsertSqlPropertyMaybeIf(tableInfo, prefix), "", "", null, ",");
        String keyProperty = null;
        String keyColumn = null;
        String methodName = "insertNotExist";
        if (StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
            if (tableInfo.getIdType() == IdType.AUTO) {
                keyGenerator = new Jdbc3KeyGenerator();
                keyProperty = StringUtils.join(prefix, tableInfo.getKeyProperty());
                keyColumn = tableInfo.getKeyColumn();
            } else if (null != tableInfo.getKeySequence()) {
                keyGenerator = TableInfoHelper.genKeyGenerator(tableInfo, this.builderAssistant, methodName, this.languageDriver);
                keyProperty = StringUtils.join(prefix, tableInfo.getKeyProperty());
                keyColumn = tableInfo.getKeyColumn();
            }
        }
        String sql = String.format(ExpandSqlUtils.getInsertNotExistSql(), tableInfo.getTableName(), columnScript, valuesScript, tableInfo.getTableName(), this.sqlWhereEntityWrapper(true, tableInfo));
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, methodName, sqlSource, keyGenerator, keyProperty, keyColumn);
    }
}
